﻿using AutoMapper;
using ImageMagick;
using ManagementApi.Models.Notify;
using ManagementApi.Models.System.TableLog;
using Modules.CheckIn.Entitys;
using Modules.Entitys;
using Modules.Notify;
using Modules.Project.Models;
using NPOI.SS.Formula.Functions;
using PmSoft.ApplicationContext;
using PmSoft.Logging;

namespace ManagementApi.Models;

/// <summary>
/// 首页统计
/// </summary>
public class HomeStatisticDto : HomeStatistic
{
    /// <summary>
    /// 西藏工人占比
    /// </summary>
    public string PersonXZRatio { get; set; }

    /// <summary>
    /// 出勤率
    /// </summary>
    public string AttendanceRatio { get; set; }

    /// <summary>
    /// 缺勤人数
    /// </summary>
    public int AbsenceAttendance { get; set; }

    /// <summary>
    /// 代发总额
    /// </summary>
    public decimal TotalPaymentAmount { get; set; }

    /// <summary>
    /// 签订合同占比
    /// </summary>
    public string SignContractRatio { get; set; }

    /// <summary>
    /// 系统通知
    /// </summary>
    public IEnumerable<SysNotifyDto>? Notifys { get; set; }

    /// <summary>
    /// 操作动态
    /// </summary>
    public IEnumerable<SysTableLogDto>? TableLog { get; set; }
}

/// <summary>
/// 扩展字段
/// </summary>
public static partial class HomeStatisticExceptions
{
    /// <summary>
    /// 转为返回实体
    /// </summary>
    /// <param name="statistic"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public static HomeStatisticDto AsDto(this HomeStatistic statistic, IApplicationContext context)
    {
        var sysNotifyService = context.GetService<SysNotifyService>();
        var sysTableLogService = context.GetService<SysTableLogService>();
        var mapper = context.GetService<IMapper>();
        HomeStatisticDto dto = new();
        mapper.Map(statistic, dto);

        if (dto.PersonCount > 0)
        {
            dto.PersonXZRatio = ((Convert.ToDecimal(dto.PersonXZCount) / Convert.ToDecimal(dto.PersonCount)) * 100).ToString("0.00");
            dto.SignContractRatio = ((Convert.ToDecimal(dto.SignPersonCount) / Convert.ToDecimal(dto.PersonCount)) * 100).ToString("0.00");
        }
        if (dto.NumberAttendees > 0)
        {
            dto.AttendanceRatio = ((Convert.ToDecimal(dto.ActualAttendance) / Convert.ToDecimal(dto.NumberAttendees)) * 100).ToString("0.00");
        }
        dto.AbsenceAttendance = dto.NumberAttendees - dto.ActualAttendance;
        dto.TotalPaymentAmount = dto.OfflinePaymentAmount + dto.OnlinePaymentAmount;
        dto.Notifys = sysNotifyService.GetSysNotifysByPage(new NotifyQuery(), 1, 10).AsSysNotifyDtos();
        dto.TableLog = sysTableLogService.GetLogs(new SysTableLogQuery(), 1, 10).AsDtos();
        return dto;
    }
}